import eventBus from "@/eventBus";
import { debounce } from '@/utils';
import defaultJpg from "@/assets/haiou.webp"

let imgs = [];

//处理单张图片
function setImage(img) {
    img.dom.src = defaultJpg
    //处理图片,该图片是否在视口范围内
    const clientHeight = document.documentElement.clientHeight;  //视口高度
    const rect = img.dom.getBoundingClientRect();
    const hieght = rect.height || 150
    if (rect.top >= -hieght || rect.top < clientHeight) {
        //在视窗内
        // const tempImg = new Image()
        // tempImg.onload = function () {
        //     //当真实图片加载完成之后
        //     img.dom.src = img.src;
        // }
        // tempImg.src = img.src;
        img.dom.src = img.src;
        imgs = imgs.filter(i => i !== img);   //处理后移除图片
    }


}

//调用该函数就可设置那些合适的图片
function setImages() {
    for (const img of imgs) {
        setImage(img)
    }
}

//滑动的时候调用
function handleScroll(dom) {
    setImages()
}

setInterval

eventBus.$on("mainScroll", debounce(handleScroll, 50))

export default {
    inserted(el, bindings) {
        const img = {
            dom: el,
            src: bindings.value,
        }
        imgs.push(img);
        //立即处理一次
        setImages()
    },
    unbind(el) {
        imgs = imgs.filter(img => img.dom !== el)
    }
}